package com.xymtop.api.aop;


import com.xymtop.api.inspector.Ins;
import com.xymtop.api.utils.JsonResoult;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * @ClassName : InsAspet
 * @Description : 审查切面
 * @Author : 肖叶茂
 * @Date: 2022/12/13  10:36
 */

@Aspect
@Component
public class InsAspet {

    @Autowired
    private ApplicationContext applicationContext;

    @Around("execution(* com.xymtop.api.controller..*(..))")
    public Object Around(ProceedingJoinPoint joinPoint) throws Throwable {
         Object resoult = null;
        Boolean flag = true;
        //       调用之前，需要处理参数
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        List<Object> args = Arrays.asList(joinPoint.getArgs());
        Map<String,Ins> insList =  applicationContext.getBeansOfType(Ins.class);
        for(Map.Entry value : insList.entrySet()){
            Method method = value.getValue().getClass().getDeclaredMethod("startTask",List.class);
            Object tempObj = Thread.currentThread().getContextClassLoader().loadClass(value.getValue().getClass().getCanonicalName()).newInstance();

            Object res =  method.invoke(tempObj,args);

            if(res instanceof  Boolean){
                if(!(Boolean) res ){
                    flag = (Boolean) res;
                }

            }
        }

        if(flag){
            resoult = joinPoint.proceed();
        }else {
            return new JsonResoult<>(500,"","参数违规,审查不通过");
        }

        return  resoult;

    }

}

